/*
 * @Descripttion: 监听 localStorage 或 sessionStorage 的变化
 * @Author: liuxiaoling
 * @Date: 2021-04-18 17:28:25
 * @LastEditors: liuxiaoling
 * @LastEditTime: 2021-04-18 17:31:14
 */

/**
 * @description 监听 localStorage 或 sessionStorage 的变化
 * @author liuxiaoling
 * @param { number } type 1 localStorage 2 sessionStorage
 * @param { string } key 键
 * @param { string } data 要存储的数据
 */
const addStorageEvent = function(type, key, data) {
  if (type === 1) {
    // 创建一个StorageEvent事件
    let newStorageEvent = document.createEvent('StorageEvent')
    const storage = {
      setItem: function(k, val) {
        localStorage.setItem(k, val)
        // 初始化创建的事件
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null)
        // 派发对象
        window.dispatchEvent(newStorageEvent)
      }
    }
    return storage.setItem(key, data)
  } else {
    // 创建一个StorageEvent事件
    let newStorageEvent = document.createEvent('StorageEvent')
    const storage = {
      setItem: function(k, val) {
        sessionStorage.setItem(k, val)
        // 初始化创建的事件
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null)
        // 派发对象
        window.dispatchEvent(newStorageEvent)
      }
    }
    return storage.setItem(key, data)
  }
}

export default addStorageEvent
